package cliente;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.StringTokenizer;

public class Cliente implements Runnable {

    private Socket server;
    private PrintStream ps;
    private BufferedReader is;
    private String nick = "";
    private int nickLock, joinLock, createLock  = 1;

    public int connect(String ip, int port) {
        return connectTo(ip, port);
    }

    public int connect(String ip) {
        return connectTo(ip, 7000);
    }

    public int connect() {
        return connectTo("127.0.0.1", 7000);
    }

    public int createChannel(String name) {
        ps.println("CREATECHANNEL:{name=\"#" + name + "\"}");
        createLock = 2;
        while (createLock == 2) {
        }   
        return createLock;
    }

    public int joinChannel(String name) {
        ps.println("JOINCHANNEL:{name=\"#" + name + "\"}");
        joinLock = 2;

        while (joinLock == 2) {
        }

        return joinLock;
    }

    private int connectTo(String ip, int port) {
        try {
            //Cria o socket com o recurso desejado na porta especificada  
            this.server = new Socket(ip, port);

            //Cria a Stream de saida de dados  
            this.ps = new PrintStream(server.getOutputStream());


            //SERVERCONNECT PROTOCOL
            //"SERVERCONNECT:{nick="%NICK%"}
            ps.println("SERVERCONNECT:{nick=\"" + (nick.isEmpty() ? "" : nick) + "\"}");


            //Cria a Stream de entrada de dados
            this.is = new BufferedReader(new InputStreamReader(server.getInputStream()));
            String retorno = is.readLine();
            if (retorno.contains("SERVERCONNECT")) {
                if (retorno.contains("status=\"Accept\"")) {
                    Thread t = new Thread(this);
                    t.start();
                    System.out.println("OK");
                    return 0;
                } else if (retorno.contains("status=\"Refuse\"")) {
                    System.out.println("SHIT");
                    return -1;
                }
            } else {
                System.out.println(retorno);
            }

        } catch (IOException e) {  //Trata possíveis exceções
            
            System.out.println("Erro aqui.");
        }

        return -1;
    }

    public void setNick(String nick) {
        this.nick = nick;
    }

    public int changeNick(String nick) {
        ps.println("CHANGENICK:{toNick=\"" + nick + "\"}");
        nickLock = -2;

        while (nickLock == -2) {
        }

        return nickLock;
    }

    public void disconnect() {
        ps.println("DISCONNECTUSER:{}");
    }

    public void sendMessage(String message, String destination) {
        ps.println("MESSAGE:{msg=\"" + message + "\",toUser=\"" + destination + "\"}");
        //TODO
    }
    
    public void indentifyMsg(String msg) {
         String str;
         String splitedStr[] = msg.split(":");
                if (splitedStr[0].compareToIgnoreCase("CHANGENICK") == 0) {
                    str = splitedStr[1].substring(1, splitedStr[1].length() - 1);
                    String splitedStr1[] = str.split(",");
                    for(int i = 0; i < splitedStr1.length; i++) {
                        String splitedStr2[] = splitedStr1[i].split("=");
                        if (splitedStr2[0].compareToIgnoreCase("status") == 0) {
                            if (splitedStr2[1].compareToIgnoreCase("\"Accept\"") == 0) {
                                nickLock = 0;
                            }
                         
                        } else if (splitedStr2[0].compareToIgnoreCase("errorNum") == 0) {
                            nickLock = Integer.parseInt(splitedStr2[1].substring(1, splitedStr2[1].length() - 1));
                        } else {
                            System.out.println(splitedStr2[0]);
                        }
                            
                    }
                } else if (splitedStr[0].compareToIgnoreCase("CREATECHANNEL") == 0) {
                     str = splitedStr[1].substring(1, splitedStr[1].length() - 1);
                    String splitedStr1[] = str.split(",");
                    for(int i = 0; i < splitedStr1.length; i++) {
                        String splitedStr2[] = splitedStr1[i].split("=");
                        if (splitedStr2[0].compareToIgnoreCase("status") == 0) {
                            if (splitedStr2[1].compareToIgnoreCase("\"Accept\"") == 0) {
                                createLock = 0;
                            }
                         
                        } else if (splitedStr2[0].compareToIgnoreCase("errorNum") == 0) {
                            createLock = Integer.parseInt(splitedStr2[1].substring(1, splitedStr2[1].length() - 1));
                        } else {
                            System.out.println(splitedStr2[0]);
                        }
                            
                    }
                } else if (splitedStr[0].compareToIgnoreCase("JOINCHANNEL") == 0) {
                     str = splitedStr[1].substring(1, splitedStr[1].length() - 1);
                    String splitedStr1[] = str.split(",");
                    for(int i = 0; i < splitedStr1.length; i++) {
                        String splitedStr2[] = splitedStr1[i].split("=");
                        if (splitedStr2[0].compareToIgnoreCase("status") == 0) {
                            if (splitedStr2[1].compareToIgnoreCase("\"Accept\"") == 0) {
                                joinLock = 0;
                            }
                         
                        } else if (splitedStr2[0].compareToIgnoreCase("errorNum") == 0) {
                            joinLock = Integer.parseInt(splitedStr2[1].substring(1, splitedStr2[1].length() - 1));
                        } else {
                            System.out.println(splitedStr2[0]);
                        }
                            
                    }
                }
    }

    @Override
    public void run() {
        try {
            String retorno;
            while ((retorno = is.readLine()) != null) { //TODO -Tratar errossss
                System.out.println(retorno);
                indentifyMsg(retorno);
            }
        } catch (IOException e) {
        }
    }
}